from fastapi import FastAPI, HTTPException, Cookie, status
from fastapi.responses import JSONResponse, FileResponse
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from typing import Dict
import json

app = FastAPI()


class ProductRequest(BaseModel):
    name: str
    description: str | None = None
    price: int


class Product(ProductRequest):
    id: int


store: Dict[int, Product] = {}


@app.post("/products")
async def API_create_new_product(product: ProductRequest):
    new_product = Product(id=len(store), name=product.name, description=product.description, price=product.price)

    store[new_product.id] = new_product

    return JSONResponse({"id": new_product.id}, status_code=status.HTTP_201_CREATED)


@app.get("/products/{product_id}")
async def API_get_product(product_id: int):
    product = store.get(product_id)

    if product is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"product with id={product_id} not found")
    else:
        return JSONResponse(jsonable_encoder(product), status_code=status.HTTP_200_OK)


@app.get("/products_download")
async def API_download_products():
    products_list = list(store.values())

    with open("products.json", "w") as f:
        json.dump(jsonable_encoder(products_list), f, indent=4)

    return FileResponse("products.json", headers={"Content-Type": "", "Content-Disposition": "attachment; filename=products_list.json"})
